<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form :form="form" slot="detail">
        <a-tabs v-model="activeKey" type="editable-card" @edit="onEdit">
          <a-tab-pane v-for="(pane,index) in panes" :key="pane.key" :tab="pane.title" :closable="pane.closable" forceRender>
            <a-row>
              <a-col :span="13">
                <a-form-item label="批次名称" :labelCol="labelCol1" :wrapperCol="wrapperCol">
                  <a-input v-if="isDisable" style="width: 200px" v-model="pane.title" :disabled="isDisable"
                           placeholder="批次"></a-input>
                  <a-input v-else style="width: 200px" v-model="inputcontent" :disabled="isDisable"
                           placeholder="批次"></a-input>
                  <a-button v-show="isDisable" style="margin-left: 10px" type="primary"
                            @click="changeName(pane.title)" icon="edit">
                    修改
                  </a-button>
                  <a-button v-show="!isDisable" style="margin-left: 10px" @click="changeNameCance(index)">
                    取消
                  </a-button>
                  <a-button v-show="!isDisable" style="margin-left: 10px" type="primary"
                            @click="confirmName(index)">
                    确定
                  </a-button>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="11">
                <a-form-item label="关联主单号" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                  <a-select
                    mode="multiple" style="width: 200px;" v-model="pane.customsNumber">
                    <a-select-option v-for="item in mainOffNumbersData" :key="item" :value="item">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="关联箱号" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                  <a-select
                    mode="multiple" style="width: 200px;" v-model="pane.boxNumber">
                    <a-select-option v-for="item in boxNumberData" :key="item" :value="item">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报关行" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <!--                  <a-select style="width: 200px" v-model="pane.customsBroker">-->
                  <!--                    <div slot="dropdownRender" slot-scope="menu">-->
                  <!--                      <v-nodes :vnodes="menu"/>-->
                  <!--                      <a-divider style="margin: 4px 0;"/>-->
                  <!--                      <div-->
                  <!--                        style="padding: 4px 8px; cursor: pointer;"-->
                  <!--                        @mousedown="e => e.preventDefault()"-->
                  <!--                        @click="addItem"-->
                  <!--                      >-->
                  <!--                        <a-icon type="plus"/>-->
                  <!--                        Add item-->
                  <!--                      </div>-->
                  <!--                    </div>-->
                  <!--                    <a-select-option v-for="item in items" :key="item" :value="item">-->
                  <!--                      {{ item }}-->
                  <!--                    </a-select-option>-->
                  <!--                  </a-select>-->
                  <a-select v-model="pane.customsBroker"
                            placeholder="请选择报关行">
                    <div slot="dropdownRender" slot-scope="menu">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0;" />
                      <div
                        style="padding: 4px 8px; cursor: pointer;"
                        @mousedown="e => e.preventDefault()"
                        @click="addForeignAgentItem()"
                      >
                        <a-icon type="plus-circle" />
                        添加报关行
                      </div>
                    </div>
                    <a-select-option v-for="(item, key) in dictForeignAgentOptions" :key="key" :value="item.value">
                      {{ item.text }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item label="报关时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-date placeholder="请选择报关时间" v-model="pane.customsTime"
                          :show-time=true date-format="YYYY-MM-DD HH:mm:ss" :trigger-change="true"
                          style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报关单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="pane.customsOdd" placeholder="0"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报检号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-button type="primary" @click="showModel(1,index)" size="small">
                    <a-icon type="plus" />
                    添加
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="卫生证书编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-button type="primary" @click="showModel(2,index)" size="small">
                    <a-icon type="plus" />
                    添加
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="厂号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-button type="primary" @click="showModel(3,index)" size="small">
                    <a-icon type="plus" />
                    添加
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="监管方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-dict-select-tag
                    v-model="pane.supervisionMode"
                    dictCode="jgfs"
                    showSearch="false"
                    placeholder="请选择" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="监管条件" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="pane.supervisionConditions"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="手册号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="pane.manualNumber"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报关贸易方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="pane.customsType"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报关查验时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-date placeholder="请选择时间" v-model="pane.customsChaTime" :trigger-change="true"
                          style="width: 100%" :show-time=true date-format="YYYY-MM-DD HH:mm:ss" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="报检查验时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <j-date placeholder="请选择时间" v-model="pane.inspectionChaTime" :trigger-change="true"
                          style="width: 100%" :show-time=true date-format="YYYY-MM-DD HH:mm:ss" />
                </a-form-item>
              </a-col>

              <a-col :span="21">
                <a-form-item label="验货地" :labelCol="labelCol2" :wrapperCol="wrapperCol">
                  <div v-for="(item,i) in pane.place">
                    <a-input style="width: 300px" placeholder="详细地址" v-model="item.content" />
                    <a-date-picker style="width: 160px;margin-left: 10px" v-model="item.time" :show-time=true
                                   date-format="YYYY-MM-DD HH:mm:ss" placeholder="验货时间" />
                    <a-icon
                      v-if="pane.place.length >1"
                      style="margin-left: 10px"
                      class="dynamic-delete-button"
                      type="minus-circle-o"
                      @click="removeAddress(pane.place,i)"
                    />
                    <a-button v-if="pane.place.length - 1 == i" type="dashed"
                              style="margin-left: 10px;width: 100px;color: darkgreen"
                              @click="addAddress(pane.place,i)">
                      <a-icon type="plus" />
                      增加
                    </a-button>

                  </div>
                </a-form-item>

              </a-col>

              <!--              <a-col :span="8">-->
              <!--                <a-form-item label="报关件数" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-input v-model="pane.customsJS" placeholder="0" suffix="PKG" :disabled="true"></a-input>-->

              <!--                </a-form-item>-->
              <!--              </a-col>-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-item label="报关毛重" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-input v-model="pane.customsMZ" placeholder="0" suffix="KGS" :disabled="true"></a-input>-->
              <!--                </a-form-item>-->
              <!--              </a-col>-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-item label="报关体积" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-input v-model="pane.customsTJ" placeholder="0" suffix="CBM" :disabled="true"></a-input>-->
              <!--                </a-form-item>-->
              <!--              </a-col>-->

            </a-row>
            <j-vxe-table
              ref="vTable"
              toolbar
              row-number
              row-selection
              keep-source
              :height="580"
              :loading="loading"
              :dataSource="pane.goodsList"
              :columns="columns2"
              style="margin-top: 8px;"
              @valueChange="handleValueChange"
              bordered
            >

            </j-vxe-table>
          </a-tab-pane>
        </a-tabs>
        <a-modal
          title="添加报关行"
          :visible="foreignAgentModalVisible"
          :maskClosable="false"
          :confirm-loading='confirmLoading'
          @ok="addHandleOkGys"
          @cancel="addHandleCancelGys"
        >
          <a-input placeholder="请输入报关行" v-model="newForeignAgentTitle" :allowClear=true></a-input>
        </a-modal>


      </a-form>
    </j-form-container>
    <div style="margin-top: 30px"></div>
    <div
      :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 999,
        }"
    >
      <a-button :style="{ marginRight: '8px' }" @click="allclose">
        关闭
      </a-button>
      <a-button type="primary" @click="saveForm">
        保存
      </a-button>
    </div>
    <a-modal v-model="modalVisible" :title="modalTitle" ok-text="保存" cancel-text="取消" @ok="okModal">

      <a-select mode="tags" style="width: 100%" v-model="modalValue" placeholder="请输入"
      >

      </a-select>
    </a-modal>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import JDate from '@/components/jeecg/JDate'
import moment from 'moment'
import { pushIfNotExist, randomNumber, randomUUID } from '@/utils/util'
import { ajaxGetDictItems } from '@api/api'
import JAreaLinkage from '@comp/jeecg/JAreaLinkage'
import Vue from 'vue'

let index = 0
export default {
  name: 'DeclareForm',
  components: {
    JFormContainer,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {

    const panes = [
      {
        title: '批次1', key: '1',
        customsNumber: [],
        boxNumber: [],
        customsBroker: '',
        customsTime: '',
        customsOdd: '',
        nspectionNumber: [],
        healthNumber: [],
        factoryNumber: [],
        supervisionMode: '',
        supervisionConditions: '',
        manualNumber: '',
        customsType: '',
        customsChaTime: '',
        inspectionChaTime: '',
        place: [{}],
        customsJS: '',
        customsMZ: '',
        customsTJ: '',
        goodsList: [],
        closable: false
      }
    ]
    return {

      dddd: [
        {
          'unit': 'WOODEN CASES',
          'number': 111,
          'source': '111',
          'volume': 111,
          'cointype': 'CNY',
          'orderNum': 1,
          'goodscost': 11,
          'maoweight': 111,
          'jingweight': 11,
          'chinesename': '111'
        }
      ],
      foreignAgentModalVisible: false,
      dictForeignAgentOptions: [],
      newForeignAgentTitle: '',
      modalTitle: '',
      modalValue: [],
      modalType: 0,
      modalIndex: 0,
      modalVisible: false,
      mainOffNumbersData: [],
      boxNumberData: [],
      loading: false,
      columns2: [
        {
          title: '中文品名',
          key: 'chinesename',
          type: JVXETypes.input,
          width: '180px'
        },
        {
          title: '原产地',
          key: 'source',
          type: JVXETypes.input,
          width: '180px',
          defaultValue: '',
          placeholder: '请输入${title}'
        },
        {
          title: '货物费用',
          key: 'goodscost',
          type: JVXETypes.inputNumber,
          width: '100px',
          defaultValue: 0
        },
        {
          title: '币种',
          key: 'cointype',
          type: JVXETypes.select,
          width: '100px',
          options: [],
          dictCode: 'currency',
          placeholder: '请选择'
        },
        {
          title: '件数',
          key: 'number',
          type: JVXETypes.inputNumber,
          width: '80px',
          defaultValue: 0,
          statistics: ['sum', 'average']
        },
        {
          title: '单位',
          key: 'unit',
          type: JVXETypes.select,
          width: '150px',
          options: [],
          dictCode: 'total_type',
          placeholder: '请选择'
        },
        {
          title: '毛重(KGS)',
          key: 'maoweight',
          type: JVXETypes.inputNumber,
          width: '120px',
          defaultValue: 0,
          statistics: ['sum', 'average']
        },
        {
          title: '净重(KGS)',
          key: 'jingweight',
          type: JVXETypes.inputNumber,
          width: '120px'
        },
        {
          title: '体积(CBM)',
          key: 'volume',
          type: JVXETypes.inputNumber,
          width: '120px',
          statistics: ['sum', 'average']
        }
      ],
      newTabIndex: 1,
      items: ['jack', 'lucy'],
      inputcontent: '',
      selectNames: ['1', '2', '3', '4', '5'],

      isDisable: true,
      activeKey: panes[0].key,
      panes,
      customStyle:
        'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden',

      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      labelCol1: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      labelCol3: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol3: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/box.ship/shipInfo/baoguan/add',
        edit: '/declare/declare/edit',
        querybgById: '/box.ship/shipInfo/baoguan/queryByShipId'
      },
      isrefresh: 0
    }
  },
  computed: {},
  created() {
    this.isDisable = true
    this.initDict()
  },
  watch: {
    panes: {
      handler() {
        this.isrefresh += 1
        if (this.isrefresh > 1) {
          this.$emit('isEditFunctino', true)
        }
      },
      deep: true
    }
  },
  methods: {

    questId(id) {
      console.log('id:' + id)
      this.modelId = id
      this.selectAllNumber(id)

    },
    praseStrEmpty(str) {
      if (!str || str == 'undefined' || str == 'null') {
        return ''
      }
      return str
    },
    selectAllNumber(id) {
      console.log('selectAllNumberid:' + id)
      console.log('selectAllNumberid:' + this.url.querybgById)
      var that = this
      let httpurl = ''
      httpurl += this.url.querybgById
      let params = { 'shipId': id }
      getAction(httpurl, params).then((res) => {
        if (res.success) {

          console.log(res)
          that.boxNumberData = JSON.parse(res.result.boxNumberData)
          that.mainOffNumbersData = JSON.parse(res.result.mainOffNumbersData)
          if (res.result.declareAtCustomsInfoList.length == 0) {
            return
          }
          that.panes = res.result.declareAtCustomsInfoList

          that.panes.map(function(panes, K) {

            panes.key = K + 1 + ''
            that.newTabIndex = K + 1
            for (var key in panes) {
              panes[key] = that.praseStrEmpty(panes[key])
            }
            panes.customsNumber = JSON.parse(panes.customsNumber)
            panes.factoryNumber = JSON.parse(panes.factoryNumber)
            panes.goodsList = JSON.parse(panes.goodsList)
            console.log(panes.goodsList)
            panes.healthNumber = JSON.parse(panes.healthNumber)
            panes.nspectionNumber = JSON.parse(panes.nspectionNumber)
            panes.place = JSON.parse(panes.place)
            panes.boxNumber = JSON.parse(panes.boxNumber)
          })
          console.log(that.panes)
          console.log(that.panes[0].goodsList)
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    initDict() {
      let a = Vue.ls.get('Login_Userinfo')
      ajaxGetDictItems('foreign_agent_info,title,id,sys_org_code=\'' + a.orgCode + '\'', null).then((res) => {
        if (res.success) {
          this.dictForeignAgentOptions = res.result
        }
      })
    },
    /**
     * 报关行添加
     */
    addForeignAgentItem() {
      this.foreignAgentModalVisible = true
    },
    addHandleOkGys(e) {
      let customerVal = this.newForeignAgentTitle.trim().replaceAll(' ', '')
      let url = '/box.common/add/foreignAgent', method = 'post'
      let value = { 'customerTitle': customerVal }
      if (customerVal) {
        httpAction(url, value, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.foreignAgentModalVisible = false
            this.dictForeignAgentOptions.unshift({ 'value': res.result, 'text': customerVal, 'title': customerVal })
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.newForeignAgentTitle = ''
        })
      }
    },
    addHandleCancelGys(e) {
      this.foreignAgentModalVisible = false
      this.newForeignAgentTitle = ''
    },
    okModal() {
      if (this.modalType === 1) {
        this.panes[this.modalIndex].nspectionNumber = this.modalValue
      } else if (this.modalType === 2) {
        this.panes[this.modalIndex].healthNumber = this.modalValue
      } else if (this.modalType === 3) {
        this.panes[this.modalIndex].factoryNumber = this.modalValue
      }
      this.modalVisible = false
    },
    showModel(type, index) {
      this.modalVisible = true
      if (type === 1) {
        this.modalTitle = '报检号'
        this.modalValue = this.panes[index].nspectionNumber
        this.modalType = type
        this.modalIndex = index
      } else if (type === 2) {
        this.modalTitle = '卫生证书编号'
        this.modalValue = this.panes[index].healthNumber
        this.modalType = type
        this.modalIndex = index
      } else if (type === 3) {
        this.modalTitle = '厂号'
        this.modalValue = this.panes[index].factoryNumber
        this.modalType = type
        this.modalIndex = index
      }
    },
    saveForm() {
      var that = this
      this.panes.map(function(pane, index) {

        console.log(that.$refs.vTable[index].getTableData())
        pane.goodsList = that.$refs.vTable[index].getTableData()
        console.log(pane)
      })
      console.log(that.panes)
      let formvalues = {
        declareAtCustomsInfoList: that.panes,
        shipId: that.modelId
      }
      console.log(formvalues)
      that.confirmLoading = true
      console.log(this.panes)
      let httpurl = this.url.add
      let method = 'post'
      let formData = Object.assign({}, formvalues)

      // console.log('表单提交数据', formData)
      httpAction(httpurl, formData, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.$emit('allOk')
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    allclose() {
      this.$emit('allclose')
    },
    handleCK(props) {
      this.$message.success('请在控制台查看输出')
      // 参数介绍：
      // props.value          当前单元格的值
      // props.row            当前行的数据
      // props.rowId          当前行ID
      // props.rowIndex       当前行下标
      // props.column         当前列的配置
      // props.columnIndex    当前列下标
      // props.$table         vxe实例，可以调用vxe内置方法
      // props.target         JVXE实例，可以调用JVXE内置方法
      // props.caseId         JVXE实例唯一ID
      // props.scrolling      是否正在滚动
      // props.triggerChange  触发change事件，用于更改slot的值
      console.log('查看: ', { props })
    },

    handleDL(props) {
      // 调用删除方法
      props.target.removeRows(props.row)
    },

    handleValueChange(event) {
      console.log('handleValueChange.event: ', event)
    },

    /** 表单验证 */
    handleTableCheck() {
      this.$refs.vTable.validateTable().then(errMap => {
        if (errMap) {
          console.log('表单验证未通过：', { errMap })
          this.$message.error('验证未通过，请在控制台查看详细')
        } else {
          this.$message.success('验证通过')
        }
      })
    },

    /** 获取值，忽略表单验证 */
    handleTableGet() {
      const values = this.$refs.vTable.getTableData()
      console.log('获取值:', { values })
      this.$message.success('获取值成功，请看控制台输出')
    },

    addItem() {
      console.log('addItem')
      this.items.push(`New item ${index++}`)
    },
    confirmName(index) {
      if (!this.inputcontent) {
        this.$message.error('内容不可为空!')

        return
      }
      this.panes[index].title = this.inputcontent
      this.isDisable = true

      // pane.key+'a'"
      // console.log(this.$refs)
    },
    changeName(value) {
      this.isDisable = false
      this.inputcontent = value

    },
    changeNameCance(index) {
      this.isDisable = true
      // this.panes[index].content =  this.panes[index].title
    },
    callback(key) {
      console.log(key)
    },
    onEdit(targetKey, action) {
      this.isDisable = true
      this[action](targetKey)
    },
    add() {
      const panes = this.panes
      const activeKey = `批次${this.newTabIndex++}`
      panes.push({
        title: '批次' + this.newTabIndex, key: activeKey,
        customsNumber: [],
        boxNumber: [],
        customsBroker: '',
        customsTime: '',
        customsOdd: '',
        nspectionNumber: [],
        healthNumber: [],
        factoryNumber: [],
        supervisionMode: '',
        supervisionConditions: '',
        manualNumber: '',
        customsType: '',
        customsChaTime: '',
        inspectionChaTime: '',
        place: [{}],
        customsJS: '',
        customsMZ: '',
        customsTJ: '',
        goodsList: []
      })
      this.panes = panes
      this.activeKey = activeKey
      this.panes.forEach((pane, i) => {
        pane.closable = true
      })
    },
    remove(targetKey) {
      this.isDisable = true
      let activeKey = this.activeKey
      let lastIndex
      this.panes.forEach((pane, i) => {
        if (pane.key === targetKey) {
          lastIndex = i - 1
        }
      })
      const panes = this.panes.filter(pane => pane.key !== targetKey)
      if (panes.length && activeKey === targetKey) {
        if (lastIndex >= 0) {
          activeKey = panes[lastIndex].key
        } else {
          activeKey = panes[0].key
        }
      }
      if (panes.length == 1) {
        panes[0].closable = false
      }
      this.panes = panes
      this.activeKey = activeKey
    },
    removeAddress(item, index) {
      item.splice(index, 1)
    },
    addAddress(item, k) {

      if (!item[k].content || item[k].content == '') {

        this.$message.error('内容不可为空！')

        return
      }
      if (!item[k].time || item[k].time == '') {

        this.$message.error('请选择时间！')

        return
      }
      // let values ={};
      item.push({})
    }

  }
}
</script>